import localforage from 'localforage';
import { cloneDeep } from 'lodash';
import { rootKey, rootDefault } from './mateLocalConst';

import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 16);

//获取本地文件夹信息
function checkAndLoadFolderList() {
  return localforage.getItem(rootKey).then(retObj => {
    if (retObj == null) {
      retObj = cloneDeep(rootDefault);
      localforage.setItem(rootKey, retObj);
    }
    return retObj;
  });
}

// 初始化文件夹信息
function initFolderNode(pFolderName) {
  const tmpId = nanoid();
  const type = 'folder';
  return {
    title: pFolderName,
    nodeIcon: 'md-folder',
    nodeType: type,
    nodeId: tmpId,
    parentId: 'root',
    fileInfo: {
      name: pFolderName,
      type: type,
      size: 0,
      lastModified: new Date().getTime(),
    },
    children: [],
  };
}

// 初始化文件信息
function initFileNode(curFile, parentId) {
  const tmpId = nanoid();
  return {
    title: curFile.name,
    nodeIcon: 'ios-document-outline',
    nodeType: 'file',
    nodeId: tmpId,
    parentId: parentId,
    fileKey: 'file_' + tmpId,
    fileInfo: {
      name: curFile.name,
      type: curFile.type,
      size: curFile.size,
      lastModified: curFile.lastModified,
    },
    children: [],
  };
}

export { checkAndLoadFolderList, initFolderNode, initFileNode };